<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2015/8/10
 * Time: 17:54
 */
namespace Home\Controller;

use Think\Controller;
use Think\Log;

/**
 * 支付
 * Class BuyController
 * @package Home\Controller
 */
class BuyController extends Controller
{
    /**
     * 订单确认
     */
    public function confirm()
    {
        $schemaTable = M("schema_info", "jt_");
        $buyerInfoTable = M("buyer_info", "jt_");
        session("openId",getOpenId());//保存openId，以备ajax用
        $schedule = $schemaTable->where("SchID='%s'",I('schId'))->select();
        $buyerInfo = $buyerInfoTable->where("openId='%s'",session("openId"))->order('create_time desc')->select();
        $this->assign("buyerlist", $buyerInfo);
        $this->assign("schedule", $schedule[0]);
        $this->display();
    }

    /**
     * 根据取票人姓名,电话,身份证返回其id
     * @param $name
     * @param $phone
     * @param $identity
     * @return mixed
     */
    private function getBuyerId($name,$phone,$identity){
        $buyerTable = M("buyer_info","jt_");
        $condition['name'] = $name;
        $condition['phone'] = $phone;
        $condition['identity'] = $identity;
        $buyer = $buyerTable -> where($condition) -> field('id') -> find();
        //Log::write(json_encode($buyer));
        if(!$buyer){
            $buyer['id'] = getUUIDShort();
            $buyer['name'] = $name;
            $buyer['phone'] = $phone;
            $buyer['identity'] = $identity;
            $buyer['openId'] = session('openId');
            $buyer['create_time'] = array("exp","now()");
            $buyerTable -> add($buyer);
        }
        Log::write($buyer['id']);
        return $buyer['id'];
    }

    /**
     * 提交订单并锁票处理
     */
    public function ticketLock()
    {
        $name = I('name');
        $phone = I('phone');
        $identity = I('identity');
        $buyerId = $this -> getBuyerId($name,$phone,$identity);//得到取票人id
        $payType="3";//支付类型

        $post_string = "cmd=TicketLock&args={param:{stationCode:'" . I('stationCode') . "',schID:'" . I('schID') . "',lockInfo:'" . I('lockInfo') . "',cTicketNo:'',payType:'".$payType."',ticketQty:'" . I('ticketQty') . "',ticketFee:'" . I('ticketFee') . "',ticketAmt:'" . I('ticketAmt') . "',insAmt:'',openID:'".session('openId')."',buyerid:'".$buyerId."'}}";
        $json = post(C('REMOTE_INTERFACE_BASE_URL'), $post_string);
        $jsonObj = json_decode($json,true);
        if($jsonObj["retcode"]!=0)
        {
            $this->ajaxReturn(array("status"=>"fail","msg"=>$post_string));
        }

        $this->ajaxReturn(array("status"=>"ok","orderId"=>$jsonObj['data']['list'][0]['orderID'],"buyerId"=>$buyerId));
    }
    /**
     * 支付
     */
    public function pay()
    {
        $orderId=I('get.orderId');
        $orderModel=M('order_info','jt_')->where("orderID='%s'",$orderId)->find();
        $orderModel['number'] = strlen($orderModel['lockinfo']);//票张数
        //dump($orderModel);die;
        $schemaModel = M("schema_info", "jt_")->where("SchID='%s'",$orderModel["schid"])->find();
        $buyerModel = M("buyer_info","jt_") -> where("id='%s'",$orderModel['buyerid']) -> field("name,phone,identity") -> find();
        //todo 向微信提交订单
        $tools = getTools();
        $openId = getOpenId();
        if($openId == ""){
            $openId = I("get.openId");
        }
        $totalFee = (int)((float)$orderModel['ticketamt'] * 100);
        $totalFee=(int)((float)$totalFee/1000);
        $notifyUrl="http://www.jsscom.com:9090/kyz/weChatPaymentServlet";
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("车站购票");
        $input->SetAttach("车站购票");
        $input->SetOut_trade_no($orderId);
        $input->SetTotal_fee($totalFee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("车站购票");
        $input->SetNotify_url($notifyUrl);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        //dump($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign("orderModel",$orderModel);
        $this->assign("schemaModel",$schemaModel);
        $this->assign("jsApiParameters",$jsApiParameters);
        $this->assign("buyerModel",$buyerModel);
        if("wait" == I("get.referer")){//请求自 我的订单的未支付订单
            $this -> assign("referer","wait");
        }
        $this->display();
    }
}